from flask import Flask,request
from pyicloud import PyiCloudService
from json import dumps
from bson import json_util, ObjectId

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
from pymongo.errors import DuplicateKeyError

from pyicloud.exceptions import (
    PyiCloudAPIResponseError,
    PyiCloudBinaryFeedParseError,
    PyiCloudPhotoLibraryNotActivatedErrror
)

import time

app = Flask(__name__)

#uri = "mongodb://user:password@example.com/the_database"
client = MongoClient("mongodb://119.29.165.135:27017/?maxPoolSize=10")
m_users = client["crawler"]["users"]
m_users.ensure_index("email", unique=True)
m_messages = client["crawler"]["messages"]

status = [0,1,2] #0 init, 1 using, 2 accept

@app.route("/")
def hello():
    return "Hello World!"

@app.route("/users")
def users():
    page = request.args.get('start')
    if page is None:
        page = 0
    else:
        page = int(page)
    size = request.args.get('length')
    if size is None:
        size = 10
    else:
        size = int(size)

    cursor = m_users.find().skip(page).limit(size)

    data = []
    for i in cursor:
        data.append(i)
    return json_util.dumps({'data': data})

@app.route("/messages")
def messages():
    page = request.args.get('start')
    if page is None:
        page = 0
    else:
        page = int(page)
    size = request.args.get('length')
    if size is None:
        size = 10
    else:
        size = int(size)

    cursor = m_messages.find().skip(page).limit(size)

    data = []
    for i in cursor:
        data.append(i)
    return json_util.dumps({'data': data})


@app.route("/post", methods=['POST'])
def post():

    message = 'error'
    if request.form['startDate'] is None:
        return message
    if request.form['endDate'] is None:
        return message
    if request.form['title'] is None:
        return message
    if request.form['location'] is None:
        return message

    startDate = request.form['startDate']
    endDate = request.form['endDate']
    title = request.form['title']
    location = request.form['location']
    invitees = request.form['invitees']
    frequency = request.form['frequency']

    #todo change account auto matically
    username = 'whenjonny@gmail.com'
    password = 'Aa3101914'
    api = PyiCloudService(username, password, './pyicloud/cookies')

    subscribe = 1

    while True:
        frequency = int(frequency) - subscribe
        if frequency < 0:
            break

        cur_time = int(time.time())
        if invitees is None or invitees == "":
            invitees_array = []
            for user in m_users.find({'status': 0}).limit(subscribe):
                invitees_array.append(user['email'])
        else:
            invitees_array = invitees.split("\n")

        try:
            guid = api.calendar.post('home', title, location, startDate=startDate, endDate=endDate, invitees=invitees_array)
        except PyiCloudAPIResponseError as err:
            print err
            continue

        for email in invitees_array:
            m_users.update({'email': email}, {
                "email": email,
                "times": 0,
                "status": 1,
                "update_time": cur_time,
                "create_time": cur_time
            }, True);

        m_messages.insert({
            'account': username,
            'title': title,
            'location': location,
            'guid': guid,
            'invitees': invitees_array,
            'accepts': 0,
            'subscribe': subscribe,
            'status': 0,
            'create_time': cur_time,
            'update_time': cur_time
        })
        time.sleep(10)

    return "success"

if __name__ == "__main__":
    app.run(debug=True)
